#!usr/bin/env python
#coding=utf8

from tuangou.models.tuan_models import Item, ItemImage, ItemCategory, ItemLinkItemCategory
from tuangou.common_logic import commutil

def get_category_list():
    categories = ItemCategory.objects.filter(level=1).order_by('index')
    for category in categories:
        category.subItems = category.children.all()
        
    return categories

def get_top_category_list():
    categories = ItemCategory.objects.filter(level=1).order_by('index')
        
    return categories

def add_category(data):
    c = ItemCategory()
    c.title = data['title']
    c.index = data['index']
    c.parent_id = data['parent_id']
    c.level = data['level']
    c.save()

def save_category(id, data):
    c = get_category_by_id(id)
    if c:
        c.title = data['title']
        c.index = data['index']
        c.parent_id = data['parent_id']
        c.level = data['level']
        c.save()    

def delete_category(id):
    category = get_category_by_id(id)
    if category:
        if category.level==1:
            for c in category.children.all():
                ItemLinkItemCategory.objects.filter(itemcategory=c.id).delete()
                c.delete()
        else:
            ItemLinkItemCategory.objects.filter(itemcategory=category.id).delete()
        category.delete()

def get_category_by_id(id):
    try:
        category = ItemCategory.objects.get(id=id)
    except:
        category = None
        
    return category

def get_category_ids(category):
    '''
    获取第一级分类所包含的id
    '''
    arr = category.children.all() #ItemCategory.objects.get(parent=category.id)
    arrIds = []
    arrIds.append(str(category.id))
    if arr:
        for a in arr:
            arrIds.append(str(a.id))
                
    return arrIds
    
def get_item_list_by_category(category, page, page_size, order_by='-createdtime'):
    '''
    获取第二级分类的商品
    '''
    page, page_size, offset = commutil.get_page_offset(page, page_size)
    items = category.items.order_by(order_by)[offset : offset + page_size]
    for item in items:
        item.price = commutil.decimalFormat(item.price)
        item.tuanprice = commutil.decimalFormat(item.tuanprice)
        try:
            item.homeimage = item.itemimage_set.filter(imagetype='home')[0]
        except:
            item.homeimage = ItemImage(thumburl='', imagetype='home', originalurl='')
            
    return items

def get_item_by_category_count(category):
    '''
    获取第二级分类商品的个数
    '''
    return category.items.count()

def get_item_list_by_top_category(category, page, page_size, order_by='-createdtime'):
    '''
    获取第一级分类的商品
    '''
    page, page_size, offset = commutil.get_page_offset(page, page_size)
    order = commutil.get_order_by(order_by)
    childrenIds = get_category_ids(category)
    where = ''
    if len(childrenIds) > 0 :
        for id in childrenIds:
            where = where + id + ','
        where = where[0 : len(where) - 1]
    sql = 'SELECT item.* FROM item INNER JOIN itemlinkitemcategory ON item.id=itemlinkitemcategory.item_id AND itemlinkitemcategory.itemcategory_id IN(' + where + ') ORDER BY %s LIMIT ' + str(offset) + ',' + str(page_size)
    q = Item.objects.raw(sql, [order])
    items = []
    for item in q:
        item.price = commutil.decimalFormat(item.price)
        item.tuanprice = commutil.decimalFormat(item.tuanprice)
        try:
            item.homeimage = item.itemimage_set.filter(imagetype='home')[0]
        except:
            item.homeimage = ItemImage(thumburl='', imagetype='home', originalurl='')
            
        items.append(item)
  
    sql = 'SELECT COUNT(1) AS id FROM item INNER JOIN itemlinkitemcategory ON item.id=itemlinkitemcategory.item_id AND itemlinkitemcategory.itemcategory_id IN(' + where + ')'
    q = Item.objects.raw(sql)
    try:
        item_count = q[0].id
    except:
        item_count = 0
        
    return items, item_count

def get_top_category_item_list(category, top_size, order_by='-createdtime'):
    order = commutil.get_order_by(order_by)
    childrenIds = get_category_ids(category)
    where = ''
    if len(childrenIds) > 0 :
        for id in childrenIds:
            where = where + id + ','
        where = where[0 : len(where) - 1]
    sql = 'SELECT item.* FROM item INNER JOIN itemlinkitemcategory ON item.id=itemlinkitemcategory.item_id AND itemlinkitemcategory.itemcategory_id IN(' + where + ') ORDER BY %s LIMIT 0,' + top_size
    q = Item.objects.raw(sql, [order])
    items = []
    for item in q:
        items.append(item)
        
    return items

def get_menu_category():
    menuCategorys = []
    categories = ItemCategory.objects.filter(level=1).order_by('index')
    length = len(categories)
    if length == 0:
        return menuCategorys
    #每三个一组
    menuCategory = None
    count = 2
    for i in range(0, length):
        if i % count == 0:
            menuCategory = ItemCategory()
            menuCategory.data = []
            if i == 0 :
                menuCategory.first = True
            menuCategorys.append(menuCategory)
        category = categories[i]
        category.first = (i % count == 0)
        category.subItems = category.children.all()
        category.hotItems = get_top_category_item_list(category, '5', '-createdtime')
        menuCategory.data.append(category)
        
    return menuCategorys










    